//
//  String+Extension.swift
//  HappyCharge
//
//  Created by 虞淞晴 on 2018/5/6.
//  Copyright © 2018年 zjxdqh. All rights reserved.
//

import Foundation

import CommonCrypto



extension String {
    
    /// 字符串的匹配范围 方法二(推荐)
    ///
    /// - Parameters:
    ///     - matchStr: 要匹配的字符串
    /// - Returns: 返回所有字符串范围
    @discardableResult
    func hw_exMatchStrRange(_ matchStr: String) -> [NSRange] {
        var selfStr = self as NSString
        var withStr = Array(repeating: "X", count: (matchStr as NSString).length).joined(separator: "") //辅助字符串
        if matchStr == withStr { withStr = withStr.lowercased() } //临时处理辅助字符串差错
        var allRange = [NSRange]()
        while selfStr.range(of: matchStr).location != NSNotFound {
            let range = selfStr.range(of: matchStr)
            allRange.append(NSRange(location: range.location,length: range.length))
            selfStr = selfStr.replacingCharacters(in: NSMakeRange(range.location, range.length), with: withStr) as NSString
        }
        return allRange
    }
    
    static func isPhoneNumber(phoneNumber:String) -> Bool {
        if phoneNumber.count == 0 {
            return false
        }
        let mobile = "^(13[0-9]|15[0-9]|18[0-9]|17[0-9]|147)\\d{8}$"
        let regexMobile = NSPredicate(format: "SELF MATCHES %@",mobile)
        if regexMobile.evaluate(with: phoneNumber) == true {
            return true
        }else
        {
            return false
        }
    }
    
    func convertDictionaryToJSONString(dict:Dictionary<String,Any>)->String {
        let data = try? JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted)
        let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        var newJson = jsonStr
        newJson = newJson?.replacingOccurrences(of: " ", with: "") as NSString?
        newJson = newJson?.replacingOccurrences(of: "\n", with: "") as NSString?

        return newJson! as String
    }
    
    
    
    //字典转JSON
    func dicToString(dictionary:Dictionary<String,Any>) -> String {
        
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
        
    }
    
    //Str转时间戳
    func stringConvertTimestamp(string:String, dateFormat:String) -> Int {
        
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = dateFormat
        let date = dateFormatter.date(from: string)
        let timeStr:TimeInterval = (date?.timeIntervalSince1970)!
        return Int(timeStr)
        
    }
    
    //时间戳转日期组件
    
    public static func dateFormTimestamp(timestamp:String)->DateComponents{
        let date = Date.init(timeIntervalSince1970: TimeInterval(timestamp)!)
        //获取当前的Calendar(用于作为转换Date和DateComponents的桥梁)
        let calendar = Calendar.current
        //使用（时区+时间）重载函数进行转换（这里参数in使用TimeZone的构造器创建了一个东七区的时区）
        let dateComponets1 = calendar.dateComponents(in: TimeZone.init(secondsFromGMT: 3600*7)!, from: date)
        //输出结果（通过DateComponents对象点出对应的时间成分）
     
        //使用另一个重载函数进行转换（第一个参数给一个Set集合对象，你给了哪些时间成分对象就可以在后面得到对应的成分）
        let dateComponets2 = calendar.dateComponents([Calendar.Component.year,Calendar.Component.month,Calendar.Component.day], from: date)
     
        return dateComponets1
    }
    
    
    //date转string
    
    func dateToYearMDHM(date1:Date) -> String {
        
        let dfmatter = DateFormatter()
        dfmatter.dateFormat="yyyy-MM-dd HH:mm"
        
        let currentDateStr = dfmatter.string(from: date1)
        
        return currentDateStr
        
    }
    
    //date转string
    
    func dateToTimeMDHM(date1:Date) -> String {
        
        let dfmatter = DateFormatter()
        dfmatter.dateFormat="HH:mm"
        
        let currentDateStr = dfmatter.string(from: date1)
        
        return currentDateStr
        
    }
    
    func dateToOnlyYear(date1:Date) -> String {
        
        let dfmatter = DateFormatter()
        dfmatter.dateFormat="yyyy"
        
        let currentDateStr = dfmatter.string(from: date1)
        
        return currentDateStr
        
    }
    
    func dateToOnlyYearMoth(date1:Date) -> String {
        
        let dfmatter = DateFormatter()
        dfmatter.dateFormat="yyyy-MM"
        
        let currentDateStr = dfmatter.string(from: date1)
        
        return currentDateStr
        
    }
    
    //date转string
    
    func dateToYearMothMDHM(date1:Date) -> String {
        
        let dfmatter = DateFormatter()
        dfmatter.dateFormat="yyyy-MM-dd"
        
        let currentDateStr = dfmatter.string(from: date1)
        
        return currentDateStr
        
    }
    
    func getXingQiJiAction() -> String {
        
        let calendar:Calendar = Calendar(identifier: .gregorian)
        var comps:DateComponents = DateComponents()
        comps = calendar.dateComponents([.year,.month,.day,.weekday,.hour,.minute,.second], from: Date())
        
        let weekDay = comps.weekday! - 1
        
        
        let array = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]
        let week = array[weekDay]
        return week
        
    }
    
    func dateToYearDateMDHM(date1:Date) -> String {
        
        let dfmatter = DateFormatter()
        dfmatter.dateFormat="yyyy年MM月dd日 HH:mm"
        
        let currentDateStr = dfmatter.string(from: date1)
        
        return currentDateStr
        
    }
    
    func dateToZJXDYearMDHM(date1:Date) -> String {
        
        let dfmatter = DateFormatter()
        dfmatter.dateFormat="yyyy"
        
        let currentDateStr = dfmatter.string(from: date1)
        
        return currentDateStr
        
    }
    
    //时间戳转date的string
    func TimestampToDateForYearMDHM(timeStamp:String) -> String {
        
        let string = NSString(string: timeStamp)
        
        let timeSta:TimeInterval = string.doubleValue
        
        let dfmatter = DateFormatter()
        
        dfmatter.dateFormat="yyyy-MM-dd HH:mm"
        
        let date = Date(timeIntervalSince1970: timeSta)
        
        let currentDateStr = dfmatter.string(from: date)
        
        return currentDateStr
    }
    
    func TimestampToYMD(timeStamp:String) -> String {
        
        let string = NSString(string: timeStamp)
        
        let timeSta:TimeInterval = string.doubleValue
        
        let dfmatter = DateFormatter()
        
        dfmatter.dateFormat="yyyy-MM-dd"
        
        let date = Date(timeIntervalSince1970: timeSta)
        
        let currentDateStr = dfmatter.string(from: date)
        
        return currentDateStr
    }
    
    func TimestampToMD(timeStamp:String) -> String {
        
        let string = NSString(string: timeStamp)
        
        let timeSta:TimeInterval = string.doubleValue
        
        let dfmatter = DateFormatter()
        
        dfmatter.dateFormat="MM-dd"
        
        let date = Date(timeIntervalSince1970: timeSta)
        
        let currentDateStr = dfmatter.string(from: date)
        
        return currentDateStr
    }
    
    //
    func StringToDateForYearMDHM(dateString:String) -> Date {
        
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let date = dateFormatter.date(from: dateString)
        
        
        return date!
    }
    
    func StringToDateFortimeMDHM(dateString:String) -> Date {
        
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = "mm:ss"
        let date = dateFormatter.date(from: dateString)
        
        
        return date!
    }

    

    var length:Int { return (self as NSString).length }
        
    var bool:Bool { return (self as NSString).boolValue }
    
    var integer:NSInteger { return (self as NSString).integerValue }
    
    var float:Float { return (self as NSString).floatValue }
    
    var cgFloat:CGFloat { return CGFloat(self.float) }
    
    var double:Double { return (self as NSString).doubleValue }
    
    /// 文件后缀(不带'.')
    var pathExtension:String { return (self as NSString).pathExtension }
    
    /// 文件名(带后缀)
    var lastPathComponent:String { return (self as NSString).lastPathComponent }
    
    /// 文件名(不带后缀)
    var deletingPathExtension:String { return (self as NSString).deletingPathExtension }
    
    /// 去除首尾空格
    var removeSpaceHeadAndTail:String { return trimmingCharacters(in: NSCharacterSet.whitespaces) }
    
    /// 去除首尾换行
    var removeEnterHeadAndTail:String { return trimmingCharacters(in: NSCharacterSet.whitespaces) }
    
    /// 去除首尾空格和换行
    var removeSEHeadAndTail:String { return trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) }
    
    /// 去掉所有空格
    var removeSapceAll:String { return replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "　", with: "") }
    
    /// 去除所有换行
    var removeEnterAll:String { return replacingOccurrences(of: "\r", with: "").replacingOccurrences(of: "\n", with: "") }
    
    /// 去除所有空格换行
    var removeSapceEnterAll:String { return removeSapceAll.replacingOccurrences(of: "\n", with: "") }
    
    /// 是否为整数
    var isInt:Bool {
        
        let scan: Scanner = Scanner(string: self)
        
        var val:Int = 0
        
        return scan.scanInt(&val) && scan.isAtEnd
    }
    
    /// 是否为数字或Float
    var isFloat:Bool {
        
        let scan: Scanner = Scanner(string: self)
        
        var val:Float = 0
        
        return scan.scanFloat(&val) && scan.isAtEnd
    }
    
    /// 是否为空格
    var isSpace:Bool {
        
        if (self == " ") || (self == "　") { return true }
        
        return false
    }
    
    /// 是否为空格或者回车
    var isSpaceOrEnter:Bool {
        
        if isSpace || (self == "\n") { return true }
        
        return false
    }
    
    /// MD5加密
    var md5:String {
        
        let string = cString(using: String.Encoding.utf8)
        
        let stringLength = CUnsignedInt(lengthOfBytes(using: String.Encoding.utf8))
        
        let digestLength = Int(CC_MD5_DIGEST_LENGTH)
        
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLength)
        
        CC_MD5(string!, stringLength, result)
        
        let hash = NSMutableString()
        
        for i in 0 ..< digestLength { hash.appendFormat("%02x", result[i]) }
        
        result.deinitialize(count: digestLength)
        
        return String(format: hash as String)
    }
    
    /// 转JSON
    var json:Any? {
        
        let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false)
        
        let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
        
        return json
    }
    
    /// 是否包含指定字符串
    func range(_ string: String) ->NSRange {
        
        return (self as NSString).range(of: string)
    }
    
    /// 截取字符串
    func substring(_ range:NSRange) ->String {
        
        return (self as NSString).substring(with: range)
    }
    
    /// 处理带中文的字符串
    func addingPercentEncoding(_ characters: CharacterSet = .urlQueryAllowed) ->String {
        
        return (self as NSString).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
    }
    
    /// 正则替换字符
    func replacingCharacters(_ pattern:String, _ template:String) ->String {
        
        do {
            let regularExpression = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
            
            return regularExpression.stringByReplacingMatches(in: self, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, length), withTemplate: template)
            
        } catch {return self}
    }
    
    /// 正则搜索相关字符位置
    func matches(_ pattern:String) ->[NSTextCheckingResult] {
        
        if isEmpty {return []}
        
        do {
            let regularExpression = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
            
            return regularExpression.matches(in: self, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, length))
            
        } catch {return []}
    }
    
    /// 计算大小
    func size(_ font:UIFont, _ size:CGSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)) ->CGSize {
        
        let string:NSString = self as NSString
        
        return string.boundingRect(with: size, options: [.usesLineFragmentOrigin,.usesFontLeading], attributes: [.font:font], context: nil).size
    }
    
    
}

extension NSAttributedString {
    
    /// 计算size
    func size(_ size:CGSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)) ->CGSize{
        
        return self.boundingRect(with: size, options: [NSStringDrawingOptions.usesLineFragmentOrigin,NSStringDrawingOptions.usesFontLeading], context: nil).size
    }
    
    /// 扩展拼接
    func add<T:NSAttributedString>(_ string:T) ->NSAttributedString {
        
        let attributedText = NSMutableAttributedString(attributedString: self)
        
        attributedText.append(string)
        
        return attributedText
    }



}

extension String {

    

    ///去掉字符串标签

    mutating func filterHTML() -> String?{

        

        let scanner = Scanner(string: self)

        

        var text: NSString?

        while !scanner.isAtEnd {

            

            scanner.scanUpTo("<", into: nil)

            scanner.scanUpTo(">", into: &text)

           self = self.replacingOccurrences(of: "\(text == nil ? "" : text!)>", with: "")


        }

        return self

    }

}

